import 'package:flutter/material.dart';
import 'package:happy_elf_app/apis/home.dart';
import 'package:happy_elf_app/store/config.dart';
import 'package:happy_elf_app/store/home.dart';
import 'package:happy_elf_app/utils/adaption.dart';
import 'package:happy_elf_app/utils/globalKey.dart';
import 'package:happy_elf_app/utils/themColor.dart';

class Summary extends StatefulWidget {
  const Summary({super.key});

  @override
  State<Summary> createState() => _SummaryState();
}

class _SummaryState extends State<Summary> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  final HomeDataProvider = Provider.of<HomeData>(
    Global.navigatorKey.currentContext!,
    listen: false,
  );

  Map summaryInfo = {'summary': '', 'stepList': []};
  int selectedIndex = -1; // 选中的任务节点索引
  Map? selectedStep; // 选中的任务数据

  @override
  void initState() {
    super.initState();
    getSummary();
    _controller = AnimationController(vsync: this);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void getSummary() async {
    String targetId = HomeDataProvider.target['id'].toString();
    var res = await Home().getReport(targetId);
    print('targetId$res');
    if (res['code'] == 200) {
      setState(() {
        summaryInfo = res['data'];
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // 处理stepList空安全
    List stepList = summaryInfo['stepList'] ?? [];
    List<int> feelings = stepList.map<int>((step) {
      int f = (step['feeling'] is int)
          ? step['feeling'] as int
          : int.tryParse('${step['feeling']}') ?? 2;
      return f.clamp(1, 4);
    }).toList();

    const double lineChartLeft = 60;
    const double lineChartRight = 16;
    const double lineChartTop = 20;
    const double lineChartBottom = 60;

    return SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          // 1. Summary 总结区域
          Container(
            height: 200.px,
            padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 12),
            decoration: BoxDecoration(
              color: hexColor('#E9614D'),
              borderRadius: BorderRadius.circular(8),
            ),
            child: SingleChildScrollView(
              child: Text(
                summaryInfo['summary'] ?? '暂无总结',
                style: const TextStyle(color: Colors.white, fontSize: 14),
              ),
            ),
          ),
          const SizedBox(height: 16),

          // 2. 日常情绪变化折线图卡片
          Container(
              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 4),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.4),
                    blurRadius: 4,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(children: [
                // 卡片标题
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 18, vertical: 6),
                  decoration: BoxDecoration(
                    color: hexColor('#E9614D'),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: const Text(
                    '日常情绪变化',
                    style: TextStyle(color: Colors.white, fontSize: 12),
                  ),
                ),
                const SizedBox(height: 16),

                // 折线图区域
                SizedBox(
                    height: 200,
                    child: Stack(children: [
                      // 纵轴：表情
                      Positioned(
                        left: 16,
                        top: lineChartTop,
                        bottom: lineChartBottom,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            _buildEmotionIcon(
                                'lib/assets/images/home/summary/smile-1.png'),
                            _buildEmotionIcon(
                                'lib/assets/images/home/summary/smile-2.jpg'),
                            _buildEmotionIcon(
                                'lib/assets/images/home/summary/cry.png'),
                            _buildEmotionIcon(
                                'lib/assets/images/home/summary/cry-2.png'),
                          ],
                        ),
                      ),

                      // 折线图（核心：L型坐标轴 + 折线）
                      Positioned(
                        left: lineChartLeft,
                        top: lineChartTop,
                        right: lineChartRight,
                        bottom: lineChartBottom,
                        child: CustomPaint(
                          painter: EmotionLinePainter(
                            feelings: feelings,
                            selectedIndex: selectedIndex,
                            stepCount: stepList.length,
                          ),
                        ),
                      ),

                      // 横轴：任务节点
                      Positioned(
                        left: lineChartLeft,
                        right: lineChartRight,
                        bottom: 20,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: stepList.asMap().entries.map((entry) {
                            final index = entry.key;
                            final step = entry.value;
                            return GestureDetector(
                              onTap: () {
                                setState(() {
                                  selectedIndex = index;
                                  selectedStep = step;
                                });
                              },
                              child: Container(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 8, vertical: 4),
                                decoration: BoxDecoration(
                                  color: selectedIndex == index
                                      ? hexColor('#e9614d')
                                      : Colors.transparent,
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: Text(
                                  '${index + 1}',
                                  style: TextStyle(
                                    color: selectedIndex == index
                                        ? Colors.white
                                        : Colors.grey,
                                    fontSize: 12,
                                  ),
                                ),
                              ),
                            );
                          }).toList(),
                        ),
                      )
                    ])),
              ])),
          const SizedBox(height: 16),

          // 3. 任务说明条
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: hexColor('#e9614d'),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Text(
              selectedStep != null
                  ? '任务：${selectedStep!['name']}'
                  : '请点击折线图节点查看任务详情',
              style: const TextStyle(color: Colors.white, fontSize: 16),
            ),
          ),
          const SizedBox(height: 16),

          // 4. 下拉选择和AI总结区域
          Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
            // 下拉选择
            Container(
              width: 120,
              margin: const EdgeInsets.only(right: 16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.1),
                    blurRadius: 4,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                children: [
                  Container(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 12, vertical: 10),
                    decoration: BoxDecoration(
                      color: hexColor('#e9614d'),
                      borderRadius:
                          const BorderRadius.vertical(top: Radius.circular(8)),
                    ),
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('开心',
                            style:
                                TextStyle(color: Colors.white, fontSize: 16)),
                        Icon(Icons.keyboard_arrow_down,
                            color: Colors.white, size: 18),
                      ],
                    ),
                  ),
                  const Divider(height: 1, color: Colors.grey),
                  Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                    child:
                        const Text('开心', style: TextStyle(color: Colors.grey)),
                  ),
                ],
              ),
            ),
            // AI总结
            Expanded(
              child: Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.1),
                      blurRadius: 4,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('AI总结：',
                        style: TextStyle(
                            fontSize: 16, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 8),
                    selectedStep != null
                        ? Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('任务：${selectedStep!['name']}',
                                  style: const TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500)),
                              const SizedBox(height: 4),
                              Text(
                                  '情绪反馈：${selectedStep!['feelingDescription']}（情绪值：${selectedStep!['feeling']}）',
                                  style: const TextStyle(fontSize: 14)),
                              const SizedBox(height: 4),
                              Text(
                                  '总结：这类${selectedStep!['name'].contains('分析') ? '自我觉察' : '记录'}性质的任务让你感到${selectedStep!['feelingDescription']}，可能源于对内心世界的梳理与表达带来的释放感。',
                                  style: const TextStyle(fontSize: 14)),
                            ],
                          )
                        : const Text('请点击折线图节点查看对应的AI总结',
                            style: TextStyle(fontSize: 14, color: Colors.grey)),
                  ],
                ),
              ),
            ),
          ])
        ]));
  }

  Widget _buildEmotionIcon(String assetPath) {
    return Image.asset(
      assetPath,
      width: 24,
      height: 24,
      fit: BoxFit.contain,
    );
  }
}

// 自定义折线图画笔（L型坐标轴 + 折线）
class EmotionLinePainter extends CustomPainter {
  final List<int> feelings;
  final int selectedIndex;
  final int stepCount;

  EmotionLinePainter({
    required this.feelings,
    required this.selectedIndex,
    required this.stepCount,
  });

  @override
  void paint(Canvas canvas, Size size) {
    // 画笔初始化
    final axisPaint = Paint() // 坐标轴画笔
      ..color = hexColor('#e9614d')
      ..strokeWidth = 2
      ..strokeCap = StrokeCap.round;

    final linePaint = Paint() // 折线画笔
      ..color = hexColor('#e9614d')
      ..strokeWidth = 2
      ..strokeCap = StrokeCap.round;

    final dotPaint = Paint()..style = PaintingStyle.fill;

    if (feelings.isEmpty || stepCount == 0) return;

    // 1. 绘制L型坐标轴
    // 绘制垂直上升的Y轴 (从底部到顶部)
    canvas.drawLine(Offset(0, size.height), Offset(0, 0), axisPaint);
    // 绘制水平向右的X轴 (从左到右)
    canvas.drawLine(
        Offset(0, size.height), Offset(size.width, size.height), axisPaint);

    // 2. 计算坐标点
    final List<double> yAxisPoints = [
      0,
      size.height / 3,
      2 * size.height / 3,
      size.height,
    ];

    final List<Offset> points = [];
    for (int i = 0; i < feelings.length; i++) {
      double x = size.width * (i / (stepCount - 1));
      int yIndex = 4 - feelings[i];
      double y = yAxisPoints[yIndex];
      points.add(Offset(x, y));
    }

    // 3. 绘制折线
    if (points.length > 1) {
      final path = Path()..moveTo(points[0].dx, points[0].dy);
      for (var i = 1; i < points.length; i++) {
        path.lineTo(points[i].dx, points[i].dy);
      }
      canvas.drawPath(path, linePaint);
    }

    // 4. 绘制节点
    for (int i = 0; i < points.length; i++) {
      // 选中节点的外圈
      if (i == selectedIndex) {
        canvas.drawCircle(
            points[i],
            8,
            Paint()
              ..color = hexColor('#e9614d')
              ..strokeWidth = 2
              ..style = PaintingStyle.stroke);
      }
      // 节点内圈
      dotPaint.color = i == selectedIndex ? Colors.white : hexColor('#e9614d');
      canvas.drawCircle(points[i], 4, dotPaint);
    }
  }

  @override
  bool shouldRepaint(covariant EmotionLinePainter oldDelegate) {
    return oldDelegate.feelings != feelings ||
        oldDelegate.selectedIndex != selectedIndex ||
        oldDelegate.stepCount != stepCount;
  }
}
